<template>
  <div :style="{ height: showAreaMaxHeight + 'px' }" class="tag-chart">
    <p v-if="isShowTitle" :style="{...titleStyle}" class="item-header">{{ moduleItemData.name }}</p>
    <div class="chart-content-box">
      <div :id="`tag-chart-${moduleItemData.id}`" class="chart-render-box"/>
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts';

import { TAG_MODULE_STYLE } from '@/utils/const/echarts';
import { isNumber } from '@/utils/tools';
import { moneyFilter, numberTextFormat } from '@/filters/number';
import { chartColorList } from '@/filters/status';
export default {
  components: { },
  props: {
    showAreaMaxHeight: {
      type: Number,
      default: 100
    },
    moduleItemData: {
      type: Object,
      default: () => {
        return {};
      }
    },
    columns: {
      type: Array,
      default: () => []
      // default: () => ['日期', '访问用户', '下单用户', '下单率']
    },
    rows: {
      type: Array,
      default: () => []
      // default: () => [['1/1', 1393, 5000, 50], ['1/2', 500, 4000, 32]]
    }
  },
  data() {
    return {
      TAG_MODULE_STYLE, chartColorList
    };
  },
  computed: {
    styleConfig() {
      return this.moduleItemData.styleConfig;
    },
    isBar() {
      return TAG_MODULE_STYLE.HISTOGRAM_MODULE === this.moduleItemData.moduleType;
    },
    titleStyle() {
      return this.getTitleStyle() || {};
    },
    isShowTitle() {
      return this.moduleItemData.name && !this.titleStyle.isHide;
    }
  },
  watch: {
    moduleItemData: {
      handler(data) {
        this.$nextTick(() => {
          this.initEcharts();
        });
      },
      deep: true,
      immediate: true
    }
  },
  beforeMount() {
    window.addEventListener('resize', this.resetEchart);
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.resetEchart);
  },
  methods: {
    initEcharts() {
      const dom = document.getElementById(`tag-chart-${this.moduleItemData.id}`);
      if (!dom) return;
      const myChart = echarts.init(dom);
      const data = this.getData();
      const color = chartColorList[0].colors;

      const option = {
        color,
        backgroundColor: 'transparent', // 设置图表背景图
        grid: {
          top: 30, left: 0, right: 20, bottom: 10, containLabel: true
        },
        series: this.isBar ? this.getBarSeries(data['y']) : this.getPieSeries(data)
      };
      if (this.isBar) {
        option.tooltip = {
          trigger: 'axis',
          axisPointer: { type: 'line', lineStyle: { color: '#bbbbbb5c', type: 'dashed' }}
        };
        option.xAxis = this.getXAxisConfig(data['x']);
        option.yAxis = this.getYAxisConfig();
      } else {
        option.tooltip = {
          trigger: 'item'
        };
        option.legend = {
          type: 'scroll',
          orient: 'vertical',
          right: 0, top: 0, bottom: 20, show: true };
      }
      myChart.setOption(option);
      this.myChart = myChart;
    },
    resetEchart() {
      this.myChart.resize();
    },
    getBarSeries(data) {
      return [
        {
          data,
          type: 'bar',
          barMaxWidth: 23,
          label: { // 数据标签
            show: true,
            position: 'top',
            formatter: (params) => { // 格式化数据的函数
              if (!isNumber(params.data)) {
                if (params.data instanceof Array && params.data.length === 2 && isNumber(params.data[1])) {
                  return [moneyFilter(numberTextFormat(params.data[1], 1), false)]; // params.data[0],
                }
                return params.data || '';
              } else {
                return moneyFilter(numberTextFormat(params.data, 1), false);
              }
            }
          }
        }
      ];
    },
    getPieSeries(data) {
      const list = [];
      data.x.forEach((i, index) => {
        list.push({
          value: data['y'][index],
          name: i
        });
      });
      return [
        {
          data: list,
          type: 'pie',
          label: { // 数据标签
            show: true, formatter: '{d}%'
          }
        }
      ];
    },
    getYAxisConfig() {
      return {
        type: 'value',
        splitLine: { show: true, lineStyle: { type: 'dotted' }},
        axisLine: { show: false },
        axisTick: { show: false },
        axisLabel: {
          color: '#606266', fontSize: 13,
          rotate: 0, show: true, splitLine: { show: false }, // 去除网格线
          formatter: (params) => {
            if (!isNumber(params)) {
              return params || '';
            } else {
              if (params >= 0) {
                return moneyFilter(numberTextFormat(params, 1), false);
              } else {
                return '-' + moneyFilter(numberTextFormat(Math.abs(params), 1), false);
              }
            }
          }
        }
      };
    },
    getXAxisConfig(data) {
      return {
        type: 'category',
        data,
        splitLine: { show: false }, // 去除网格线
        axisLabel: {
          show: true,
          color: '#606266',
          fontSize: 13,
          inside: false,
          rotate: 0,
          splitLine: { show: false } // 去除网格线
        },
        axisTick: { show: false },
        axisLine: { show: false }
        // z: 10
      };
    },
    getData() {
      let y = this.rows[0] || [];
      let x = this.columns || [];
      const hideColumns = [];
      const hideIndex = [];
      this.moduleItemData.tags.forEach((i) => {
        if (i.hideTag) hideColumns.push(i.tagName);
      });
      x = x.filter((i, index) => {
        if (hideColumns.includes(i)) {
          hideIndex.push(index);
          return false;
        }
        return true;
      });
      y = y.filter((i, index) => {
        return !hideIndex.includes(index);
      });

      return { x, y };
    },
    /**
     * 自定义样式
     */
    getTitleStyle() {
      const styleConfig = this.styleConfig;
      let styleObj = {};
      if (styleConfig && styleConfig instanceof Object) {
        styleObj = { ...styleConfig.moduleName };
        styleObj.lineHeight = styleObj.fontSize = styleObj.fontSize + 'px'; // 避免字体造成高度计算错误
        return styleObj;
      } else {
        return {};
      }
    }
  }
};
</script>

<style lang="scss" scoped>

.tag-chart {
  position: relative;
  width: 100%;
  display: flex;
  flex-direction: column;
  .item-header {
    font-weight: bolder;
    font-size:20px;
    color:rgba(51,51,51,1);
    margin: 0 0 12px;
  }
}
.chart-content-box {
  width: 100%;
  flex: 1;
  // padding-bottom: 100%;
  position: relative;
  // margin: 0 auto;
  .chart-render-box {
    position: absolute;
    left: 0; top: 0; bottom: 0; right: 0;
  }
}
</style>
